<?php
namespace App\Http\Controllers\Api\FlyGo;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use App\Models\Customer\Customer;
use App\Models\Card\CardCouponCode;
use App\Models\Bill\Bill;
use App\Models\Bill\BillGoods;
use App\Models\Mall\MallMaster;
use App\Service\WdhService;
use App\Models\Activity\AlipayCustomerCardMap;

class MemberCenterController extends Controller
{

    /**
     * 用户中心数据接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index( Request $request )
    {

        $userId = $request->input('userId');

        if (empty($userId)) {
            return response()->json(['code'=>100000, 'message'=>'缺少参数：userId']);
        }

        //查询用户信息
        $customer = Customer::where('pcustID',$userId)->first();
        if (!$customer) {
            return response()->json(['code'=>100006, 'message'=>'用户信息没有找到']);
        }

        //返回数据数组
        $return_data = [
            'userId' => $customer->pcustID,
            'name' => $customer->custname,
            'sexy' => $customer->sexy,
            'head_pic' => $customer->head_pic,
            'birthday' => $customer->birthday,
            'nickName' => $customer->nickName,
            'mobile' => $customer->custID,
            'card_coupon_num' => 0,
            'cardNo' => $customer->cardNo,
        ];
        //var_dump($return_data);die;

        //查询用户卡券
        $cardnum = CardCouponCode::where(['pcustID'=>$userId,'code_status'=>1])->count();

        //var_dump($cardnum);die;
        $return_data['card_coupon_num'] = $cardnum;

        return response()->json([ 'code'=>200, 'message'=>'ok', 'data'=>$return_data]);

    }


    /**
     * 修改用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit( Request $request )
    {

        $args_data = $request->all();

        //校验参数
        if (!isset($args_data['userId']) ||  !ebsig_is_int($args_data['userId'])) {
            return response()->json(['code'=>100002, 'message'=>'缺少参数:userId']);
        }

        //会员名
        if (!isset($args_data['name']) || empty($args_data['name'])) {
            return response()->json(['code'=>100002, 'message'=>'缺少参数:name']);
        }

        //昵称
        if (!isset($args_data['nickName']) || empty($args_data['nickName'])) {
            return response()->json(['code'=>100002, 'message'=>'缺少参数:nickName']);
        }

        //性别
        if (!isset($args_data['sexy']) || !in_array($args_data['sexy'], array(0, 1, 2))) {
            return response()->json(['code'=>100003, 'message'=>'参数错误:sexy']);
        }

        //生日
        if (!isset($args_data['birthday']) || empty($args_data['birthday'])) {
            return response()->json(['code'=>100002, 'message'=>'缺少参数:birthday']);
        }

        $update['pcustID'] = $args_data['userId'];
        $update['custname'] = $args_data['name'];
        $update['nickName'] = $args_data['nickName'];
        $update['birthday'] = $args_data['birthday'];


        $custdata = Customer::find($args_data['userId']);
        if (!$custdata) {
            return response()->json(['code'=>100006, 'message'=>'用户信息没有找到']);
        }
        //var_dump($custdata);die;

        $res = Customer::where('pcustID', $args_data['userId'])->update($update);
        if (!$res) {
            return response()->json(['code'=>100001, 'message'=>'用户信息修改失败']);
        }

        return response()->json(['code'=>200, 'message'=>'ok']);

    }

    /**
     * 订单列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function search( Request $request )
    {

        //用户Id
        $userId = $request->input('userId');

        //订单类型
        $type = $request->input('type');

        //每页显示条数
        $rp = $request->input('rp');

        if (!ebsig_is_int($userId) || !isset($userId)) {
            return response()->json(['code' => 100000, 'message' => '参数错误：userId']);
        }

        if ( !ebsig_is_int($rp) || !isset($rp) ) {
            $rp = 10 ;
        }

        if ( !ebsig_is_int($type) || !isset($type) ) {
            $type = 1 ;             //默认全部
        }

        //查询条件
        $where = [];
        $where[] = ['pcustID',$userId];
        //$where[] = ['is_del','=',0];
        $bill_master = [];

        switch ($type) {

            case 1 ://全部

                $bill_master = Bill::where($where)
                    ->orderBy('createTime', 'DESC')
                    ->paginate($rp)
                    ->toArray();

                break;


            case 2: //待付款

                $where[] = ['bill_status','=',0];

                $bill_master = Bill::where($where)
                    ->orderBy('createTime', 'DESC')
                    ->paginate($rp)
                    ->toArray();

                break;

            case 3: //待验货

                $where[] = ['bill_status','=',1];

                $bill_master = Bill::where($where)
                    ->orderBy('createTime', 'DESC')
                    ->paginate($rp)
                    ->toArray();

                break;

            case 4: //已完成

                $where[] = ['bill_status','=',4];

                $bill_master = Bill::where($where)
                    ->orderBy('createTime', 'DESC')
                    ->paginate($rp)
                    ->toArray();

                break;

        }
        //var_dump($bill_master);die;

        //判断订单信息是否存在
        if (!isset($bill_master['data'])) {
            return response()->json(['code' => 100001, 'message' => '未查询到订单信息']);
        }

        //返回查询数据
        $return_data = array(
            'count' => isset($bill_master['total']) ? $bill_master['total'] : 0 ,
            'bill' => array()
        );

        $status = '';
        foreach ($bill_master['data'] as $key => $list) {
            //var_dump($list['bill_no']);die;

            if($list['bill_status'] == 0){
                $status = '待付款';
            }

            if($list['bill_status'] == 1){
                $status = '待验货';
            }

            if($list['bill_status'] == 4){
                $status = '已完成';
            }

            if($list['bill_status'] == 5){
                $status = '已取消';
            }

            $bill_goods_array = [];
            //查询订单商品详情
            $bill_goods = BillGoods::where('bill_no',$list['bill_no'])->get()->toArray();

            if ( !empty($bill_goods) ) {
                foreach($bill_goods as $good) {

                    $bill_goods_array[] = [
                        'productName' => $good['goods_name'],
                        'number' => $good['goods_amount'],
                        'bill_goods_no' => strval($good['bill_goods_no']),
                        'price' => $good['goods_purchasePrice'],
                    ];

                }
            }
            //查询门店信息
            $mall_data = MallMaster::where('mallID',$list['mallID'])->first()->toArray();


            //数据组装
            $return_data['bill'][$key] = [
                'bill_no' => strval($list['bill_no']),
                'mallName' => $mall_data['mallName'],
                'create_at' => $list['createTime'],
                'user_fee' => $list['bill_payable'],
                'bill_status' => $list['bill_status'] ,
                'total_num' => $list['bill_total_amount'],
                'is_status' => $status,
                'goods' => $bill_goods_array
            ];

        }

        //var_dump($return_data);die;

        //返回数据
        return response()->json(['code'=>200,'message'=>'ok','data'=>$return_data]);

    }

    /**
     * 订单详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail( Request $request )
    {

        $bill_no = $request->input('bill_no');
        //$bill_no = '1201707180003497056';

        if ( empty($bill_no) ) {
            return response()->json(['code' => 100001, 'message' => '缺少参数：bill_no']);
        }

        //查询订单详情
        $bill_master = Bill::select('bill_no','createTime','bill_payable','bill_status','bill_total_amount')
            ->where('bill_no',$bill_no)
            ->orderBy('createTime','DESC')
            //->get()
            ->first();
        //var_dump($bill_master);die;
        if (!isset($bill_master)) {
            return response()->json(['code' => 100001, 'message' => '订单信息没有找到']);
        }


        //查询商品详情
        $bill_goods = BillGoods::where('bill_no',$bill_no)->first();
        if (!isset($bill_goods)) {
            return response()->json(['code' => 100001, 'message' => '订单商品信息没有找到']);
        }
        //var_dump($bill_goods);die;
        $bill_goods_array = [];
        if ( !empty($bill_goods) ) {

                $bill_goods_array[] = [
                    'productName' => $bill_goods->goods_name,
                    'number' => $bill_goods->goods_amount,
                    'bill_goods_no' => (string)$bill_goods->bill_goods_no,
                    'price' => $bill_goods->goods_purchasePrice,
                ];

        }
        //var_dump($bill_goods_array);die;
        $return_data = [];

            if($bill_master->bill_status == 0){
                $return_data['is_status'] = '待付款';
            }

            if($bill_master->bill_status == 1){
                $return_data['is_status'] = '待验货';
            }

            if($bill_master->bill_status == 4){
                $return_data['is_status'] = '已完成';
            }

            if($bill_master->bill_status == 5){
                $return_data['is_status'] = '已取消';
            }

            $createTime = $bill_master->createTime;
            $endTime =  date("Y-m-d H:i:s",strtotime($createTime)+15*60);
            //数据组装
            $return_data = [
                'bill_no'=> (string)$bill_master->bill_no,
                'create_at'=> $bill_master['createTime'],
                'end_time'=> $endTime,
                'user_fee'=> $bill_master->bill_payable,
                'bill_status' => $bill_master->bill_status ,
                'total_num' => $bill_master->bill_total_amount,
                'is_status' => $return_data['is_status'],
                'goods'=> $bill_goods_array,
            ];

            //var_dump($return_data);die;

        //返回数据
        return response()->json(['code'=>200,'message'=>'ok','data'=>$return_data]);

    }

    /**
     * 订单取消
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function cancel_bill( Request $request )
    {

        //$bill_no = $request->input('bill_no');
        $bill_no = '201611290000001097';
        $operator = $request->input('operator');
        $cancel_reason = $request->input('cancel_reason');

        if (!isset($bill_no) || empty($bill_no)) {
            return response()->json(['code' => 100001, 'message' => '缺少参数：bill_no']);
        }
        if (!isset($operator) || empty($operator)) {
            $operator = 'system user';
        }
        if (!isset($cancel_reason) || empty($cancel_reason)) {
            $cancel_reason = '不想买了';
        }

        $request_data = [
            'bill_no' => $bill_no,
            'operator' => $operator,
            'reason' => $cancel_reason,
        ];

        $return_data = WdhService::is_cancel($request_data);

        return response()->json(['code'=>$return_data['code'],'message'=>$return_data['message']]);

    }

    /**
     * 订单取消
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function cancel( Request $request )
    {

        $bill_no = $request->input('bill_no');  //订单号
        $pcustID = $request->input('userId'); //会员号
        $pcustID = 10001; //会员号
        $cancel_reason = $request->input('cancel_reason'); //取消原因
        $bill_status = $request->input('bill_status'); //订单状态

        if ( empty($bill_no) ) {
            return response()->json(['code' => 100001, 'message' => '缺少参数：bill_no']);
        }

        if (empty($pcustID)) {
            return response()->json(['code' => 100001, 'message' => '缺少参数：usreId']);
        }

        if (!isset($cancel_reason) || empty($cancel_reason)) {
            $cancel_reason = '手动取消订单';
        }

        if (!isset($bill_status)) {
            $bill_status = 5;   //判定订单状态为5 取消订单
        }

        $customer = Customer::select('custID')->find($pcustID);
        if (!$customer) {
            return response()->json(['code' => 100001, 'message' => '会员信息不存在']);
        }
        //var_dump($customer);die;
        $operator = $customer->custID;  //操作人

        $status_error = [
            4 => '订单已完成',
            5 => '订单已取消'
        ];

        $bill_master = Bill::getBill($bill_no);
        if (!$bill_master) {
            return response()->json(['code' => 100001, 'message' => '订单信息没有找到']);
        }
        //var_dump($bill_master);die;

        if (isset($status_error[$bill_master->bill_status])) {
            return ['code'=>$bill_master->bill_status, 'message'=>$status_error[$bill_master->bill_status]];
        }

        //订单未付款状态
        if ($bill_master->bill_status == 0) {
            //判定订单状态为5 取消订单
            $bill_master->bill_status = $bill_status;
            $bill_master->save();
        }

        //订单已经付款
        if ($bill_master->bill_status == 1) {
            //更改订单状态
            $bill_master->bill_status = $bill_status;
            $bill_master->save();

            //生成退款单
            if ( $bill_master->bill_payable > 0 && $bill_master->bill_refund_status == 0) {  //退款状态等于0 未退款
                //应付款金额大于零
                //2017年9月5日 18:15:19 doing
            }

            //进行款操作
            //查询使用优惠券
            //对已使用优惠券进行回滚
            //回滚商品库存
        }

        return response()->json(['code' => 200, 'message' => '订单取消成功']);


    }

    /**
     * 订单删除
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete( Request $request )
    {
        //$bill_no = $request->input('bill_no');
        $bill_no = '1201702060000001678';
        if ( empty($bill_no) ) {
            return response()->json(['code' => 100001, 'message' => '缺少参数：bill_no']);
        }
        $num=bill::where('bill_no','=',$bill_no)->update(['is_del'=>0]);
        dd($num);

    }

    /**
     * 优惠券列表接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function couponlist( Request $request )
    {
        //用户Id
        $userId = $request->input('userId');
        //$userId = 218468;

        //优惠券使用状态 1、未使用 2、已使用 3、已过期
        $type = $request->input('type');

        //每页显示条数
        $rp = $request->input('rp');

        if (empty($userId)) {
            return response()->json(['code'=>100001, 'message'=>'缺少参数：userId']);
        }

        if ( !ebsig_is_int($rp) ) {
            $rp = 10 ;
        }

        if ( !ebsig_is_int($type) ) {
            $type = 1 ;
        }

        //查询用户信息
        $customer = Customer::where('pcustID',$userId)->first();
        //var_dump($customer);die;
        if (!$customer) {
            return response()->json(['code'=>100006, 'message'=>'该会员不存在']);
        }

        //查询条件
        $where = [];
        $where[] = ['pcustID',$userId];

        //查询已领取未使用且未过期券码
        if ($type == 1) {
            $where[] = ['code_status',1];
            $where[] = ['code_end_time','>=',date('y-m-d h:i:s',time())];
        }
        $no_used_count = AlipayCustomerCardMap::where([['pcustID',$userId],['code_status',1],['code_end_time','>=',date('y-m-d h:i:s',time())]])->count();

        //查询已领取已使用的券码
        if ($type == 2) {
            $where[] = ['code_status',2];
        }
        $used_count = AlipayCustomerCardMap::where([['pcustID',$userId],['code_status',2]])->count();

        //查询已过期券码
        if ($type == 3) {
            $where[] = ['code_status',1];
            $where[] = ['code_end_time','<=',date('y-m-d h:i:s',time())];
        }
        $expire_count = AlipayCustomerCardMap::where([['pcustID',$userId],['code_status',1],['code_end_time','<=',date('y-m-d h:i:s',time())]])->count();

        //查询卡券信息
        $code_data = AlipayCustomerCardMap::where($where)
            ->orderBy('createTime', 'DESC')
            ->paginate($rp)
            ->toArray();

        //var_dump($code_data);die;

        $card_array = [];
        $remark = '';

        if ( !empty($code_data['data'])) {

            foreach ( $code_data['data'] as $value ) {

                $privilege_description = '';           //券使用说明
                $coupon_type_name = '';                //券名称
                $coupon_price     = '';                 //券面值价格
                switch ($value['code_use_type']){

                    case 1:
                        $coupon_type_name = '代金券';
                        $coupon_type =1;
                        $coupon_price =  $value['code_amount'];
                        $privilege_description = "购物满".$value['code_limit_amount'].'元使用';
                        $remark = '￥'.$value['code_amount'];
                        break;

                    case 2:
                        $coupon_type_name = '折扣券';
                        $coupon_type = 2;
                        $coupon_price = round($value['code_discount'] / 10,1);
                        $privilege_description = "购物满".$value['code_limit_amount'].'元使用';
                        $remark =  round($value['code_discount'] / 10,1).'折';
                        break;

                }

                $card_array[] = array(
                    'barcode' => $value['barcode'],
                    'code_use_type' => $coupon_type_name,
                    'coupon_type' => $coupon_type,
                    'remark' => $remark,
                    'activity_name' => $value['activity_name'],
                    'coupon_price'  => $coupon_price,
                    'privilege_description' => $privilege_description,//优惠说明
                    'start_time' => date('Y.m.d',strtotime($value['code_start_time'])),//有效开始时间
                    'end_time' => date('Y.m.d H:i:s',strtotime($value['code_end_time'])),//有效结束时间
                );

            }

        }
        //var_dump($card_array);die;

                //组装返回数据
                $return_data = array(
                    'no_used_count' => $no_used_count,
                    'used_count'    => $used_count,
                    'expire_count'  => $expire_count,
                    'count' => $code_data['total'],
                    'codeList' => $card_array,
                );

        //var_dump($return_data);

        return response()->json(['code'=>200,'message'=>'ok','data'=>$return_data]);

    }
}